package com.p7.framework.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.p7.framework.common.ResultBean;
import com.p7.framework.common.validator.LocaleService;
import com.p7.framework.common.validator.ValidatorUtils;
import com.p7.framework.entity.Person;

@Controller
@RequestMapping("/person")
public class PersonController {

	private static final Logger logger = LoggerFactory.getLogger(PersonController.class);

	@Autowired
	private LocaleService localeService;

	@PostMapping(value = "/createByJson", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultBean createByJson(@RequestBody @Validated Person person, BindingResult bindingResult) {

		ResultBean resultBean = ValidatorUtils.beanValid(bindingResult, localeService);
		if (null != resultBean) {
			return resultBean;
		}

		logger.info(JSON.toJSONString(person));

		return new ResultBean(person);
	}

	@PostMapping(value = "/createByForm", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultBean createByForm(Person person) {

		logger.info(JSON.toJSONString(person));

		return new ResultBean(person);
	}

	@RequestMapping(value = "/getList", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResultBean getList() {

		logger.info("--------------------------");
		return new ResultBean(getData());
	}

	private List<Person> getData() {
		List<Person> list = new ArrayList<Person>();
		Person person = new Person();
		person.setAge(18);
		person.setBirthday(new Date());
		person.setName("zhangsan");
		list.add(person);
		list.add(person);
		list.add(person);
		list.add(person);
		list.add(person);
		return list;
	}

}
